<template>

  <div class="app-container calendar-list-container">

    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="商家名"
                v-model="listQuery.name">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="电话"
                v-model="listQuery.phone">
      </el-input>
      <el-select clearable @change='handleFilter' class="filter-item" style="width: 130px"
                 v-model="listQuery.isActivation" placeholder="激活状态">
        <el-option label="激活" value="1">
        </el-option>
        <el-option label="未激活" value="0">
        </el-option>
      </el-select>
      <el-select clearable @change='handleFilter' class="filter-item" style="width: 130px"
                 v-model="listQuery.isRecommend" placeholder="是否推荐">
        <el-option label="推荐" value="1">
        </el-option>
        <el-option label="不推荐" value="0">
        </el-option>
      </el-select>

      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">新增</el-button>
      <!--<el-button class="filter-item" type="primary" :loading="downloadLoading" icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>

    <el-table :data="list.slice((currentPage-1)*pageSize,currentPage*pageSize)" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='排序ID' width="80">
        <template slot-scope="scope">
          {{scope.$index}}
        </template>
      </el-table-column>
      <el-table-column label="商家ID" width="90" align="center">
        <template slot-scope="scope">
          {{scope.row.sellerId}}
        </template>
      </el-table-column>
      <el-table-column label="名字" width="160" align="center">
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column label="电话" width="120" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.phone}}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" width="240" align="center">
        <template slot-scope="scope">
          {{scope.row.details}}
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isActivation | statusFilter">{{scope.row.isActivation === 0 ? '未激活' : '激活'}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="推荐" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isRecommend | statusFilter">{{scope.row.isRecommend === 0 ? '未推荐' : '推荐'}}</el-tag>
        </template>
      </el-table-column>

      <!--<el-table-column label="排序" width="70" align="center">
        <template slot-scope="scope">
          {{scope.row.sort}}
        </template>
      </el-table-column>-->

      <el-table-column label="时间" width="160" align="center">
        <template slot-scope="scope">
          {{scope.row.createTime}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleUpdate(scope.row)" size="mini">修改</el-button>
          <el-button size="mini" type="success" @click="handleUpload(scope.row,'seller')">商家图片</el-button>
          <el-button size="mini" type="warning" @click="handleUpload(scope.row,'manager')">经理图片</el-button>
          <!--<el-button size="mini" type="danger" >删除-->
          <!--</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <div style="padding-top: 15px;text-align: center">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page=currentPage
        :page-sizes="[10, 20, 30]"
        :page-size=pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="80px"
               style='width: 400px; margin-left:50px;'>
        <el-form-item label="名字" prop="name">
          <el-input v-model="temp.name" placeholder="商家名字"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="temp.phone" placeholder="商家电话"></el-input>
        </el-form-item>

        <el-form-item label="特色" prop="feature">
          <el-input v-model="temp.feature" placeholder="场所特色"></el-input>
        </el-form-item>

        <el-form-item label="规格" prop="spec">
          <el-input v-model="temp.spec" placeholder="场所规格"></el-input>
        </el-form-item>

        <el-form-item label="人均" prop="perCapita">
          <el-input v-model="temp.perCapita" placeholder="每人平均消费"></el-input>
        </el-form-item>

        <el-form-item label="套餐" prop="meal">
          <el-input type="textarea" :rows="3" v-model="temp.meal" placeholder="场所套餐"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="info">
          <el-input type="textarea" :rows="3" v-model="temp.info" placeholder="场所介绍"></el-input>
        </el-form-item>

        <el-form-item label="经度" prop="lng">
          <el-input v-model="temp.lat" placeholder="商家位置：经度"></el-input>
        </el-form-item>

        <el-form-item label="纬度" prop="lat">
          <el-input v-model="temp.lng" placeholder="商家位置：维度"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="details">
          <el-input v-model="temp.details" placeholder="商家地址"></el-input>
        </el-form-item>

        <el-form-item label="环境评分" prop="ambient">
          <el-input v-model="temp.ambient" placeholder="环境评分：1.0-5.0分"></el-input>
        </el-form-item>

        <el-form-item label="视觉评分" prop="vision">
          <el-input v-model="temp.vision" placeholder="视觉评分：1.0-5.0分"></el-input>
        </el-form-item>

        <el-form-item label="服务评分" prop="service">
          <el-input v-model="temp.service" placeholder="服务评分：1.0-5.0分"></el-input>
        </el-form-item>

        <el-form-item label="推荐" prop="isRecommend">
          <el-select class="filter-item" prop="isRecommend" v-model="temp.isRecommend" placeholder="请选择">
            <el-option
              v-for="item in isRecommends"
              :key="item.val"
              :label="item.name"
              :value="item.val">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="isActivation">
          <el-select class="filter-item" prop="isActivation" v-model="temp.isActivation" placeholder="请选择">
            <el-option
              v-for="item in isActivation"
              :key="item.val"
              :label="item.name"
              :value="item.val">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="temp.sort"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="buttonLoading" v-if="dialogStatus=='create'" type="primary" @click="createData">确认
        </el-button>
        <el-button :loading="buttonLoading" v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="imgMap[imgDialogStatus]" :visible.sync="dialogUploadImgVisible">

      <el-upload
        ref="imgUpload"
        action="http://upload.qiniup.com"
        :auto-upload="true"
        list-type="picture-card"
        :on-preview="showPreviewImg"
        :before-upload="beforeUpload"
        :on-success="successUpload"
        :data="qData"
        :file-list="fileList"
        :on-remove="removeImg">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="previewImgVisible" append-to-body>
        <img width="100%" :src="dialogImgUrl" alt="">
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogUploadImgVisible = false">取消</el-button>
        <el-button :loading="buttonLoading" @click="mergeUpload" type="primary">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>

  .filter-container {
    padding-bottom: 20px;
  }

</style>

<script>
  import { List, Merge } from '../../api/seller'

  import { domain, getToken } from '../../api/qiniu'

  import { listToStrs } from '../../utils/strUtil'

  export default {

    data() {
      return {
        isRecommends: [
          { name: '推荐', val: 1 },
          { name: '不推荐', val: 0 }
        ],
        isActivation: [
          { name: '未激活', val: 0 },
          { name: '激活', val: 1 }
        ],
        list: [],
        listLoading: true,
        buttonLoading: false,
        listQuery: {
          name: null,
          phone: null,
          isActivation: null,
          isRecommend: null
        },
        fileList: [],
        temp: {
          sellerId: '',
          name: '',
          phone: '',
          info: '',
          feature: '',
          spec: '',
          perCapita: '',
          isRecommend: '',
          meal: '',
          lng: '',
          lat: '',
          isActivation: '',
          sort: '',
          img: '',
          details: '',
          remarks: '',
          ambient: '',
          vision: '',
          service: ''
        },
        qData: {
          token: 'vMgCDi6neP07bVcFtdJ3IW5eLh8XJE-UVZ1-bGdd:iI5lIh-FYeji9VqSN2VLmODLCh8=:eyJzY29wZSI6InRvZ2V0aGVyIiwiZGVhZGxpbmUiOjE1MzAxODM0NTl9',
          key: ''
        },
        dialogFormVisible: false,
        dialogUploadImgVisible: false,
        dialogImgUrl: '',
        previewImgVisible: false,
        dialogStatus: '',
        downloadLoading: false,
        textMap: {
          update: '编辑商家信息：',
          create: '新增商家信息：'
        },
        imgMap: {
          seller: '商家图片',
          manager: '驻场经理图片'
        },
        imgDialogStatus: '',
        rules: {
          name: [{ required: true }],
          phone: [{ required: true }],
          info: [{ required: true }],
          feature: [{ required: true }],
          spec: [{ required: true }],
          perCapita: [{ required: true }],
          isRecommend: [{ required: true }],
          lng: [{ required: true }],
          lat: [{ required: true }],
          isActivation: [{ required: true }],
          sort: [{ required: true }],
          img: [{ required: true }],
          ambient: [{ required: true }],
          vision: [{ required: true }],
          service: [{ required: true }],
          details: [{ required: true }]
        },
        total: 0,
        currentPage: 1,
        pageSize: 10
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          // draft: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      }
    },
    created() {
      this.fetchData()
      getToken().then(res => {
        this.qData.token = res.data
      }).catch(error => {
        console.log(error)
      })
    },
    methods: {
      fetchData() {
        this.listLoading = true
        List(this.listQuery.name, this.listQuery.phone, this.listQuery.isActivation, this.listQuery.isRecommend).then(response => {
          this.list = response.data
          this.total = response.data.length
          this.currentPage = 1
          this.listLoading = false
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
      },
      handleCurrentChange(val) {
        this.currentPage = val
      },
      handleFilter() {
        this.fetchData()
      },
      handleCreate() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      handleUpdate(row) {
        this.resetTemp()
        this.temp = Object.assign(this.temp, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      },
      handleDownload() {

      },
      createData() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.buttonLoading = true
            Merge(this.temp).then(res => {
              this.temp = res.data
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.buttonLoading = false
              this.$notify({
                title: '成功',
                message: '商家创建成功',
                type: 'success',
                duration: 2000
              })
              this.fetchData()
            }).catch(reason => {
              console.log(reason)
              this.buttonLoading = false
            })
          } else {
            console.log('验证失败')
          }
        })
      },
      updateData() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.buttonLoading = true
            Merge(this.temp).then(res => {
              this.updateList(this.list, this.temp)
              this.dialogFormVisible = false
              this.buttonLoading = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }).catch(reason => {
              console.log(reason)
              this.buttonLoading = false
            })
          }
        })
      },
      updateList(list, temp) {
        for (const v of list) {
          if (this.temp.sellerId === v.sellerId) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, temp)
            break
          }
        }
      },
      updateFileList(list, row) {
        if (this.imgDialogStatus === 'seller') {
          if (row.img === null || row.img === '') return
          row.img.split(',').forEach(key => {
            list.push({ name: key, url: domain + key })
          })
        } else {
          if (row.manager === null || row.manager === '') return
          list.push({ name: row.manager, url: domain + row.manager })
        }
      },
      resetTemp() {
        this.temp = {
          sellerId: '',
          name: '',
          phone: '',
          info: '',
          feature: '',
          spec: '',
          perCapita: '',
          isRecommend: '',
          meal: '',
          lng: '',
          lat: '',
          isActivation: '',
          sort: '',
          img: '',
          details: '',
          remarks: '',
          ambient: '',
          vision: '',
          service: ''
        }
      },
      handleUpload(row, status) {
        this.resetTemp()
        this.temp.sellerId = row.sellerId
        this.imgDialogStatus = status
        this.dialogUploadImgVisible = true
        this.fileList.splice(0, this.fileList.length)// 先清空
        this.updateFileList(this.fileList, row)
      },
      removeImg(file) {
        for (var fn of this.fileList) {
          if (fn.name === file.name) {
            this.fileList.splice(this.fileList.indexOf(fn), 1)
          }
        }
      },
      beforeUpload(file) {
        this.qData.key = new Date().valueOf() + file.name
      },
      successUpload(response, file, fileList) {
        console.log(file.response)
        this.fileList.push({ name: file.response.key, url: domain + file.response.key })
        console.log(this.fileList)
      },
      mergeUpload() {
        var imgs = listToStrs(this.fileList)
        var param = {}
        if (this.imgDialogStatus === 'seller') {
          param = { sellerId: this.temp.sellerId, img: imgs }
        } else {
          param = { sellerId: this.temp.sellerId, manager: imgs }
        }
        Merge(param).then(res => {
          this.temp = res.data
          this.updateList(this.list, this.temp)
          this.dialogUploadImgVisible = false
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      showPreviewImg(file) {
        this.dialogImgUrl = file.url
        this.previewImgVisible = true
      }
    }
  }
</script>
